import {
  caret,
  open,
  OpenOptions,
  getLineId,
} from "https://raw.githubusercontent.com/takker99/scrapbox-userscript-std/0.14.1/browser/dom/mod.ts";
import {
  getIndentCount
} from "https://raw.githubusercontent.com/takker99/scrapbox-userscript-std/0.14.1/text.ts";
import type { Scrapbox } from "https://raw.githubusercontent.com/scrapbox-jp/types/0.3.3/userscript.ts";
declare const scrapbox: Scrapbox;

export const copy = (init?: Omit<OpenOptions, "body" | "id"> & { project?: string; }) => {
  if (scrapbox.Layout !== "page") return;
  
  const project = init?.project ?? scrapbox.Project.name;
  const { selectedText, selectionRange: { start, end }, } = caret();
  const id = getLineId(Math.min(start.line, end.line));
  const from = `${
    project !== scrapbox.Project.name ? `/${scrapbox.Project.name}/` : ""
  }${scrapbox.Page.title}${id ? `#${id}` : ""}`;
  
  const lines = selectedText.split("\n");
  const title = lines[0]
    .replaceAll("[", "")
    .replaceAll("]", "")
    .replaceAll("`", "");
  const minIndentCount = Math.min(...lines.map((text) => getIndentCount(text)));
  const body = [
    `from [${from}]`,
    ...lines.map((text) => text.slice(minIndentCount)),
  ].join("\n");
  open(project, title, { body, ...(init ?? {}) });
};